<template>
  <view class="outer-bg">
    <view class="container">
      <!-- 邀请二维码标题 -->
      <view class="section-title">邀请二维码</view>
      <!-- 二维码 -->
      <view class="qrcode-wrap">
        <image class="qrcode" src="/static/buddy.png" mode="aspectFit" />
      </view>
      <!-- 保存到相册 按钮 -->
      <button class="save-btn" @click="saveImage">保存到相册</button>
      
      <!-- 邀请用户列表标题 -->
      <view class="invite-list-title">
        我邀请的用户（直推{{users.length}}人）
      </view>
      <!-- 邀请记录 -->
      <view v-if="users.length > 0">
        <view v-for="(item, idx) in users" :key="item.id" class="user-row">
          <image class="avatar" :src="item.avatar" />
          <view class="info-block">
            <view class="nickname">{{ item.nickname }}</view>
            <view class="phone">{{ item.phone }}</view>
          </view>
          <view class="reg-time">{{ item.time }}</view>
        </view>
      </view>
      <view v-else class="empty-tip">
        <text>暂无邀请用户</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import sheep from '@/sheep'

const users = ref([])

// 加载邀请用户列表
const loadReferrerList = async () => {
  try {
    // 获取当前登录用户信息
    const userStore = sheep.$store('user')
    
    // 如果用户信息中没有id，先获取用户信息
    if (!userStore.userInfo?.id) {
      await userStore.getInfo()
    }
    
    const referrerId = userStore.userInfo?.id
    if (!referrerId) {
      console.log('未获取到用户ID')
      users.value = []
      return
    }
    
    const UserApi = (await import('@/sheep/api/member/user')).default
    const res = await UserApi.getUserListByReferrerId(referrerId)
    
    if (res && res.code === 0 && res.data) {
      // 处理数据，映射到页面显示的字段
      users.value = (res.data || []).map(item => ({
        id: item.id,
        avatar: item.avatar || '/static/default-avatar.png',
        nickname: item.nickname || item.username || '用户',
        phone: item.mobile ? item.mobile.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '',
        time: item.createTime ? formatTime(item.createTime) : ''
      }))
    } else {
      users.value = []
    }
  } catch (error) {
    console.error('加载邀请用户列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
    users.value = []
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    const date = new Date(timeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (e) {
    return timeStr
  }
}

function saveImage() {
  // 此处可替换为真实二维码保存逻辑
  uni.saveImageToPhotosAlbum({
    filePath: '/static/buddy.png',
    success: () => uni.showToast({title: '已保存到相册'})
  })
}

onMounted(() => {
  loadReferrerList()
})
</script>

<style lang="scss" scoped>
.outer-bg {
  background: #f6f7fa;
  min-height: 100vh;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.container {
  margin: 20rpx 16rpx 0 16rpx; 
  background: #fff;
  border-radius: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
  padding: 40rpx 34rpx 34rpx 34rpx; 
}

.section-title {
  color: #282828;
  font-size: 32rpx;
  font-weight: bold;
  margin-top: 0;
  margin-bottom: 32rpx;
  text-align: left;
}
.qrcode-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
}
.qrcode {
  width: 340rpx;
  height: 340rpx;
  border-radius: 18rpx;
  background: #eee;
}
.save-btn {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 220rpx;
  height: 70rpx;
  margin: 28rpx auto 0 auto;
  border-radius: 90rpx;
  border: none;
  font-size: 26rpx;
  font-weight: 500;
  color: #fff;
  background: linear-gradient(90deg, #9e9bfa 0%, #6dc5ff 100%);
}
.invite-list-title {
  color: #272932;
  font-weight: bold;
  font-size: 30rpx;
  margin-top: 48rpx;
  margin-bottom: 50rpx;
  text-align: left;
}
.user-row {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}
.avatar {
  width: 78rpx;
  height: 78rpx;
  border-radius: 50%;
  margin-right: 20rpx;
  background: #f0f0f0;
}
.info-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.nickname {
  font-size: 27rpx;
  color: #272932;
  font-weight: 500;
  margin-bottom: 8rpx;
}
.phone {
  font-size: 24rpx;
  color: #878a95;
}
.reg-time {
  color: #b6bcc8;
  font-size: 25rpx;
  margin-left: 16rpx;
  white-space: nowrap;
}
.empty-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200rpx;
  color: #999;
  font-size: 28rpx;
}
</style>
